using System;
using UnityEngine;

public class CameraController : MonoBehaviour
{
    [SerializeField] private Transform clampMin, clampMax;
    
    private Transform target;
    private float halfWidth, halfHeight;
    private Camera cam;

    private void Start()
    {
        target = FindAnyObjectByType<PlayerController>().transform;
        clampMax.SetParent(null);
        clampMin.SetParent(null);
        cam = GetComponent<Camera>();
        halfHeight = cam.orthographicSize;
        halfWidth = halfHeight * cam.aspect;// 摄像机的宽高比
    }

    private void Update()
    {
        transform.position = new Vector3(target.position.x, target.position.y, -10f);
        
        Vector3 calmpedPosition = transform.position;
        
        // 限制摄像机的移动范围
        calmpedPosition.x = Mathf.Clamp(calmpedPosition.x, clampMin.position.x + halfWidth, clampMax.position.x - halfWidth);
        calmpedPosition.y = Mathf.Clamp(calmpedPosition.y, clampMin.position.y + halfHeight, clampMax.position.y - halfHeight);
        
        transform.position = calmpedPosition;
    }
}
